#!/usr/bin/python3

import os
import re
import zjl_util
import uapool
import time
import getopt
import sys


class dybee:
    """
    下载电影天堂
    """

    def __init__(self):
        self.key_value_dic = {}
        self.header = {}
        uapool.UA()

    def set_header(self, header_file_path):
        if not os.path.exists(header_file_path):
            print('[warn] file: ' + header_file_path + ' not exist')
            return
        header = {}
        with open(header_file_path, 'r') as h_file:
            while h_file.readable():
                line = h_file.readline()
                sp = line.split(': ')
                if line == '':
                    break
                if len(sp) == 2:
                    k = sp[0]
                    v = sp[1].replace('\n', '')
                    header[k] = v
        self.header = header
        print(self.header)

    def down_file(self, m3u8_url):
        m3u8_doc = zjl_util.get_doc3(m3u8_url, self.header)
        print(m3u8_doc)

        m3u8_lines = m3u8_doc.split('\n')
        m3u8_result = []
        for m3u8_line in m3u8_lines:
            if m3u8_line.endswith('ts'):
                ts_url = self.get_ts_url(m3u8_url, m3u8_line)
                ts_file_name = ts_url.split('/')[-1]

                self.down_ts(ts_url, './', ts_file_name)
                m3u8_result.append(ts_file_name)
            else:
                m3u8_result.append(m3u8_line)

        m3u8_path = 'index.m3u8'
        with open(m3u8_path, 'w') as f:
                f.write('\n'.join(m3u8_result))

    def get_ts_url(self, m3u8_url, ts_uri):
        ts_url = ''
        if str(ts_uri).startswith('/'):
            ts_url = uapool.get_base_url(m3u8_url) + ts_uri
        elif str(ts_uri).startswith('http'):
            return ts_uri
        else:
            r_index = m3u8_url.rindex('/')
            ts_url = m3u8_url[0: r_index + 1] + ts_uri
            print('ts_url:', ts_url)
        return ts_url

    def down_ts(self, ts_url, dir_path, file_name):
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        i = 0
        redo_count = 0  # 用于记录下载出现错误是记录重试次数，顺利下载完后，次数归0
        while redo_count < 5:
            file_path = dir_path + "/" + file_name
            try:
                zjl_util.download(ts_url, file_path, header=self.header)
                return
            except Exception as e:
                print("request error url:" + ts_url)
                print(e)
                print('-------\t重试下载  ' + ts_url + '  \t-------')
                redo_count += 1
                time.sleep(redo_count * 30 + 1) # 每次重试增加时间
                # 提前结束本次循环，再次下载这一章
                if redo_count >= 5:
                    print('[error] 多次重试后失败')
                    exit()


def main():
    d = dybee()
    m3u8_url = 'https://vip.lzcdn2.com/20220318/12_2644b2e0/1200k/hls/mixed.m3u8'
    header_file_path = 'dytt.header.conf'

    opts, args = getopt.getopt(sys.argv[1:], "hu:H:")
    for o, a in opts:
        if o == '-h':
            print("python3 down_dybee_film.py -u " + m3u8_url + " -H " + str(header_file_path))
            exit()
        if o == '-u':
            m3u8_url = a
        if o == '-H':
            header_file_path = a
    print('m3u8地址：' + m3u8_url)

    d.set_header(header_file_path)
    d.down_file(m3u8_url)


if __name__ == "__main__":
    main()
